package cn.datawin.task.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


import cn.datawin.task.Config;
import cn.datawin.task.MainEntry;

public class WebpageScreenshot {
	
	private static WebpageScreenshot screenshot = new WebpageScreenshot();
	
	private WebDriver driver;

	private byte[] bytes;
	
	public static WebpageScreenshot getInstance(){
		return screenshot;
	}

	public WebpageScreenshot() {
		this(Config.apps.get("webdriver.firefox.bin"));
	}
	
	public WebpageScreenshot(String execPath) {
		init(execPath);
	}

	public void init(String execPath) {
		System.setProperty("webdriver.firefox.bin", execPath);
		driver = new FirefoxDriver();
	}

	public byte[] cut(String url) {
		synchronized (driver) {
			try{
				driver.manage().timeouts().implicitlyWait(2500, TimeUnit.MILLISECONDS)
					.pageLoadTimeout(2500, TimeUnit.MILLISECONDS).setScriptTimeout(2500, TimeUnit.MILLISECONDS);
				driver.get(url);
			}catch(TimeoutException timeout){
			}catch (Exception e) {
				init(Config.apps.get("webdriver.firefox.bin"));
				driver.get(url);
			}
			bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
			return bytes;
		}
	}

	public InputStream getImg() {
		return new ByteArrayInputStream(bytes);
	}

	public File toImgFile(String path) throws IOException {
		File file = new File(path);
		FileUtils.copyInputStreamToFile(getImg(), file);
		return file;
	}

	public static void main(String[] args) throws IOException {
		MainEntry.init();
		WebpageScreenshot screenshot = new WebpageScreenshot();
		screenshot.cut("http://www.taobao.com/");
		screenshot.toImgFile("d://taobao.jpg");
		screenshot.cut("http://www.baidu.com/");
		screenshot.toImgFile("d://baidu.jpg");
		screenshot.cut("http://www.58.com/");
		screenshot.toImgFile("d://58.jpg");
		screenshot.cut("http://www.ganji.com/");
		screenshot.toImgFile("d://ganji.jpg");

	}

}
